package net.dreamlu.api.oauth;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.StrKit;

import net.dreamlu.api.util.HttpKitExt;
import net.dreamlu.api.util.TokenUtil;
/**
 * OauthWeixin
 * @author Javen
 * email: javen205@126.com
 * site:  http://www.jianshu.com/u/9be31238fda1
 */
public class OauthWeixin extends Oauth{
	private static final String AUTH_URL = "https://open.weixin.qq.com/connect/qrconnect";
	private static final String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";

	
	private static OauthWeixin oauthWeixin = new OauthWeixin();

	private OauthWeixin() {}
	/**
	 * 用于链式操作
	 * @return OauthWeixin
	 */
	public static OauthWeixin me() {
		return oauthWeixin;
	}
	
	/**
	 * 获取授权url
	 * @return String url
	 */
	public String getAuthorizeUrl(String state) {
		Map<String, String> params = new HashMap<String, String>();
        params.put("appid", getClientId());
        params.put("response_type", "code");
        params.put("redirect_uri", getRedirectUri());
        params.put("scope", "snsapi_login");
        if (StrKit.isBlank(state)) {
            params.put("state", "wx#wechat_redirect");
        } else {
        	params.put("state", state.concat("#wechat_redirect"));
        }
		return HttpKitExt.initParams(AUTH_URL, params);
	}
	
	/**
	 * 获取token 返回的是JSON 解析获取到Token以及OpenId
	 * @param code 使用code换取token
	 * @return String 返回类型
	 */
	public String getTokenByCode(String code) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", code);
		params.put("appid", getClientId());
		params.put("secret", getClientSecret());
		params.put("grant_type", "authorization_code");
		return super.doPost(TOKEN_URL, params);
	}
	
	/**
	 * 获取UserInfo
	 * @param accessToken AccessToken
	 * @return String 返回类型
	 */
	public String getUserInfo(String accessToken,String openId) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		params.put("openid", openId);
		return super.doPost(USER_INFO_URL, params);
	}
	
	@Override
	public Oauth getSelf() {
		return this;
	}

}
